const express = require('express');
const router = express.Router();
const utils = require('../utils');

router.get('/',
    async (req, res, next) => {
        let locale = req.query.locale;
        locale = {
            'zh-cn': '中文',
            'en-us': '英文',
        }[locale] || '中文';

        res.addData({
            UserName: (req.user && ((req.user.Profile && req.user.Profile.Name) || req.user.PhoneNumber || req.user.UserName)) || '',
            menus: await res.app.models.menu.find({ Category: `前台主菜单 (${locale})`, Enabled: true }, {
                Parent: 1,
                Name: 1,
                Description: 1,
                Route: 1,
                Index: 1,
                Label: 1,
                Icon: 1
            }, { sort: { Index: 1 } }),
        });

        return next();
    },
);

router.get('/home',
    async (req, res, next) => {
        const commonFilter = { 
            Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true },
            ...utils.makeQueryFilters(req, 'locale'),
        };
        
        const news = res.app.models.news ? await res.app.models.news.find(commonFilter, {
            'id': 1,
            'LastUpdateDate': 1,
            '标题': 1,
            '时间': 1,
            '详情': 1,
            '类型': 1,
            '等级': 1,
            '日期': 1,
            '领域': 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', 日期: 'desc', LastUpdateDate: 'desc' } }).limit(8).lean() : [];
        news.forEach(nw => {
            nw.详情 = utils.repalceHtmlToText(nw.详情);
            nw.日期 = nw.时间 || nw.日期 || nw.LastUpdateDate;
            delete nw.LastUpdateDate;
            delete nw.时间;
        });

        const imgNews = res.app.models.news ? await res.app.models.news.find({ ...commonFilter, 轮播: true }, {
            'id': 1,
            'LastUpdateDate': 1,
            '图片': 1,
            '标题': 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', 日期: 'desc', LastUpdateDate: 'desc' } }).limit(5).lean() : [];

        const cases = res.app.models.cases ? await res.app.models.cases.find(commonFilter, {
            'id': 1,
            'LastUpdateDate': 1,
            '名称': 1,
            '时间': 1,
            '详情': 1,
            '日期': 1,
            '图片': 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', 日期: 'desc', LastUpdateDate: 'desc' } }).limit(6).lean() : [];
        cases.forEach(cs => {
            cs.详情 = utils.repalceHtmlToText(cs.详情, 1000, 5000, true, true);
            cs.日期 = cs.时间 || cs.日期 || cs.LastUpdateDate;
            delete cs.LastUpdateDate;
            delete cs.时间;
        });

        const solutions = res.app.models.solutions ? await res.app.models.solutions.find(commonFilter, {
            'id': 1,
            'LastUpdateDate': 1,
            '名称': 1,
            '时间': 1,
            '日期': 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', 日期: 'desc', LastUpdateDate: 'desc' } }).limit(6).lean() : [];
        solutions.forEach(slt => {
            slt.详情 = utils.repalceHtmlToText(slt.详情);
            slt.日期 = slt.时间 || slt.日期 || slt.LastUpdateDate;
            delete slt.LastUpdateDate;
            delete slt.时间;
        });

        const standards = res.app.models.standards ? await res.app.models.standards.find(commonFilter, {
            'id': 1,
            'LastUpdateDate': 1,
            '时间': 1,
            '发布日': 1,
            '详情': 1,
            '名称': 1,
            '范围': 1,
            '标准号': 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', 发布日: 'desc', LastUpdateDate: 'desc' } }).limit(6).lean() : [];
        standards.forEach(pol => {
            pol.详情 = utils.repalceHtmlToText(pol.详情);
            pol.日期 = pol.时间 || pol.发布日 || pol.LastUpdateDate;
            delete pol.LastUpdateDate;
            delete pol.时间;
            delete pol.发布日;
        });

        const tools = res.app.models.tool ? await res.app.models.tool.find(commonFilter, {
            'id': 1,
            标题: 1,
            图片: 1,
            描述: 1,
            详情地址: 1,
        }, { sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' } }).limit(6).lean() : [];
        tools.forEach(tool => {
            tool.详情 = utils.repalceHtmlToText(tool.详情, 1000, 5000, true, true);
            tool.日期 = tool.LastUpdateDate;
            delete tool.LastUpdateDate;
        });

        res.addData({
            news,
            imgNews,
            cases,
            solutions,

            standards,
            tools,
        });

        return next();
    },
);

router.get('/assets', async (req, res, next) => {
    const systemConf = res.app.modules['system-config'];
    let 轮播图 = req.query.bottom ? [] : await systemConf.get('轮播图', '网站设置');

    res.addData({
        轮播图: 轮播图.sort((a, b) => Number(a.index || a.auto__index || 0) - Number(b.index || b.auto__index || 0)).map((pic) => ({
            id: pic.图片 && pic.图片.id, 
            url: pic.url,
            sub: pic.sub && pic.sub.id,
            style: pic.style,
        })),
    });

    return next();
});

router.get('/flinks', async (req, res, next) => {
    const systemConf = res.app.modules['system-config'];
    let 友情链接 = req.query.bottom ? [] : await systemConf.get('友情链接', '网站设置');

    res.addData(友情链接.sort((a, b) => Number(a.index || a.auto__index || 0) - Number(b.index || b.auto__index || 0)).map((pic) => ({
        logo: pic.图片 && pic.图片.id, 
        url: pic.url,
        name: pic.name,
    })));

    return next();
});

router.get('/channel/:channel', async (req, res, next) => {
    if (!req.params.channel) return next();

    const systemConf = res.app.modules['system-config'];
    let 栏目首图 = systemConf && await systemConf.get('栏目首图', '网站设置');
    栏目首图 = 栏目首图 && 栏目首图[req.params.channel];
    栏目首图 = 栏目首图 && 栏目首图.id;

    res.addData({
        img: 栏目首图,
    });

    return next();
});

router.get('/footer', async (req, res, next) => {
    const systemConf = res.app.modules['system-config'];
    const footerInfo = systemConf && await systemConf.get('页底信息', '网站设置') || [];

    const ret = {};
    for(let i = 0; i < footerInfo.length; i += 1) {
        const ft = footerInfo[i];
        if (!ft || !ft.name) continue;
        
        ret[ft.name] = ft.value || '';
    }

    res.addData(ret);

    return next();
});

router.get('/qrcode', async (req, res, next) => {
    const systemConf = res.app.modules['system-config'];
    const qrcodes = systemConf && await systemConf.get('微信二维码', '网站设置');

    res.addData({
        qrcodes: qrcodes.map((pic) => ({id: pic.code && pic.code.id, url: pic.url, d: pic.description})),
    });

    return next();
});

router.get('/about', async (req, res, next) => {
    const locale = req.query.locale || 'zh-cn';

    const systemConf = res.app.modules['system-config'];
    const info = systemConf && await systemConf.get(`平台介绍${locale}`, '平台设置');

    res.addData({
        info,
    });

    return next();
});

// QnA
router.get('/qa',
    (req, res, next) => {
        res.locals.filter = { 
            Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true },
            ...utils.makeQueryFilters(req, 'locale'),
        };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '时间',
            '问题',
        ];
        res.locals.options = {
            lean: true,
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            limit: 1,
        };

        return next();
    },
    router.FindDocuments('qa', false, async (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];
        } else {
            res.locals.data = {};
        }
    }),
);

module.exports = router;
